﻿using UnityEngine;

[ExecuteInEditMode]
public class EasySuspension : MonoBehaviour
{
	[Range(0.1f, 20f)]
    [Tooltip("悬浮弹簧的自然频率。描述悬架的弹性")]
    //悬浮弹簧的自然频率。描述悬架的弹性
	public float naturalFrequency = 10;

	[Range(0f, 3f)]
    [Tooltip("悬架弹簧的阻尼比。描述了弹跳后弹簧返回的速度。 ")]
    //悬架弹簧的阻尼比。描述了弹跳后弹簧返回的速度。
	public float dampingRatio = 0.8f;

	[Range(-1f, 1f)]
    [Tooltip("沿y轴的距离，悬浮力施加点在质心以下偏移")]
    //沿y轴的距离，悬浮力施加点在质心以下偏移
	public float forceShift = 0.03f;

    [Tooltip("根据固有频率和阻尼比调整悬浮泉的长度。关闭时，会引起不现实的悬挂反弹。")]
    //根据固有频率和阻尼比调整悬浮泉的长度。关闭时，会引起不现实的悬挂反弹。
	public bool setSuspensionDistance = true;

    Rigidbody m_Rigidbody;

    void Start ()
    {
        m_Rigidbody = GetComponent<Rigidbody> ();
    }
    
	void Update () 
    {
        //基于较好的弹簧模型，得到了刚度和阻尼器参数。
		foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>()) 
        {
			JointSpring spring = wc.suspensionSpring;

            float sqrtWcSprungMass = Mathf.Sqrt (wc.sprungMass);
            spring.spring = sqrtWcSprungMass * naturalFrequency * sqrtWcSprungMass * naturalFrequency;
            spring.damper = 2f * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);

			wc.suspensionSpring = spring;

			Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
            float distance = m_Rigidbody.centerOfMass.y - wheelRelativeBody.y + wc.radius;

			wc.forceAppPointDistance = distance - forceShift;

            //确保最大下垂处的弹簧力完全为零
			if (spring.targetPosition > 0 && setSuspensionDistance)
				wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
		}
	}

    /*
    void OnGUI()
    {
        foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>()) {
            GUILayout.Label (string.Format("{0} sprung: {1}, k: {2}, d: {3}", wc.name, wc.sprungMass, wc.suspensionSpring.spring, wc.suspensionSpring.damper));
        }

        GUILayout.Label ("Inertia: " + m_Rigidbody.inertiaTensor);
        GUILayout.Label ("Mass: " + m_Rigidbody.mass);
        GUILayout.Label ("Center: " + m_Rigidbody.centerOfMass);
    }
    */

}
